<?php
package("Expression");
package("Expression_Operand");
package("Expression_Operator");
package("Query");
package("Utils");

/**
 * Construct a update query
 * 
 * <p>You can get a sense for how this would work for other queries by looking
 * at what follows.  Some serious questions not yet resolved are how to apply
 * this approach to cover more than one table.  I am not even positive you can
 * do an update across multiple tables in a single query, which would at least
 * alleviate the problem for this case.  That said there would still need to be
 * a way to solve the riddle for select statements.
 * 
 * TODO confirm that inserts, updates, and deletes can only involve one table
 * per a query.
 *
 */
class Query_Update implements Query_Builder {
	
	/**
	 * @var Expression_Operator
	 */
	private $_set;
	
	/**
	 * @var Expression_Operator
	 */
	private $_update;
	
	/**
	 * Queue for expressions
	 *
	 * @var Utils_Queue
	 */
	private $_queue;
	
	public function __construct() {
		$this->_queue = new Utils_Queue();
		$factory = Expression_Operator_Factory::getSingleton();
		$this->_set = $factory->construct("set", array());
		$this->_update = $factory->construct("update", array());
	}
	
	public function bindTable($table) {
		$operand = new Expression_Operand_Table($table);
		$this->_update->addOperand($operand);
		$this->_update->addOperand($this->_set);
	}
	
	public function bindKey(Core_Property $bound) {
		$factory = Expression_Operator_Factory::getSingleton();
		$column = new Expression_Operand($bound->column);
		$value = new Expression_Operand_Variable($bound->value);
		$equals = $factory->construct("equals", array($column, $value));
		$where = $factory->construct("where", array($equals));
		$this->_update->addOperand($where);
	}
	
	public function bindProperty(Core_Property $bound) {
		$factory = Expression_Operator_Factory::getSingleton();
		$column = new Expression_Operand($bound->column);
		$value = new Expression_Operand_Variable($bound->value);
		$equals = $factory->construct("equals", array($column, $value));
		$this->_queue->add($equals);
	}
	
	public function toSql() {
		$factory = Expression_Operator_Factory::getSingleton();
		$separator = $factory->construct("separator", array());
		while ($this->_queue->size() > 0) {
			$separator->addOperand($this->_queue->remove());
		}
		$this->_set->addOperand($separator);
		return $this->_update->evaluate();
	}
}
?>